package cn.iocoder.yudao.module.forward.utils;

import java.util.Random;

/**
 * snow flow .
 *https://blog.csdn.net/q20202828/article/details/147232562
 */
public class SnowflakeIdGenerator {
    // 起始时间戳（2020-01-01 00:00:00）
    private static final long START_TIMESTAMP = 1577836800000L;

    // 各部分的位数
    private static final long DATA_CENTER_ID_BITS = 5L;  // 数据中心ID占5位
    private static final long WORKER_ID_BITS = 5L;       // 工作节点ID占5位
    private static final long SEQUENCE_BITS = 12L;       // 序列号占12位

    // 最大值计算（位运算）
    private static final long MAX_DATA_CENTER_ID = ~(-1L << DATA_CENTER_ID_BITS);
    private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
    private static final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BITS);

    // 左移位数
    private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
    private static final long DATA_CENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
    private static final long TIMESTAMP_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATA_CENTER_ID_BITS;

    private static long dataCenterId;  // 数据中心ID
    private static long workerId;      // 工作节点ID
    private static long sequence = 0L;       // 序列号
    private static long lastTimestamp = -1L; // 上次生成时间

    private static Random random = new Random();
    /**
     * 构造函数
     * @param dataCenterId 数据中心ID (0~31)
     * @param workerId     工作节点ID (0~31)
     */
//    public SnowflakeIdGenerator(long dataCenterId, long workerId) {
//        if (dataCenterId > MAX_DATA_CENTER_ID || dataCenterId < 0) {
//            throw new IllegalArgumentException("DataCenter ID 超出范围");
//        }
//        if (workerId > MAX_WORKER_ID || workerId < 0) {
//            throw new IllegalArgumentException("Worker ID 超出范围");
//        }
//        this.dataCenterId = dataCenterId;
//        this.workerId = workerId;
//    }

    private static void setRandom(long dataCenterId, long workerId) {
        if (dataCenterId > MAX_DATA_CENTER_ID || dataCenterId < 0) {
            throw new IllegalArgumentException("DataCenter ID 超出范围");
        }
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException("Worker ID 超出范围");
        }
        SnowflakeIdGenerator.dataCenterId = dataCenterId;
        SnowflakeIdGenerator.workerId = workerId;
    }

    /**
     * 生成下一个ID（线程安全）
     */
    public static synchronized long nextId() {
        setRandom(random.nextInt(32), random.nextInt(32));
        long currentTimestamp = System.currentTimeMillis();

        // 时钟回拨检查
        if (currentTimestamp < lastTimestamp) {
            throw new RuntimeException("时钟回拨，拒绝生成ID");
        }

        if (currentTimestamp == lastTimestamp) {
            // 同一毫秒内序列号递增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            if (sequence == 0) {
                // 当前毫秒序列号用完，等待下一毫秒
                currentTimestamp = waitNextMillis(lastTimestamp);
            }
        } else {
            // 新毫秒重置序列号
            sequence = 0L;
        }

        lastTimestamp = currentTimestamp;

        // 组合各部分生成ID
        return ((currentTimestamp - START_TIMESTAMP) << TIMESTAMP_SHIFT)
                | (dataCenterId << DATA_CENTER_ID_SHIFT)
                | (workerId << WORKER_ID_SHIFT)
                | sequence;
    }

    /**
     * 阻塞等待直到下一毫秒
     */
    private static long waitNextMillis(long lastTimestamp) {
        long currentTimestamp = System.currentTimeMillis();
        while (currentTimestamp <= lastTimestamp) {
            currentTimestamp = System.currentTimeMillis();
        }
        return currentTimestamp;
    }

    public static void main(String[] args) {
        // 示例用法
        for (int i = 0; i < 10; i++) {
            System.out.println("生成的ID: " + SnowflakeIdGenerator.nextId());
        }
    }
}
